require "wondercap/lib/utils/logging"
require "wondercap/lib/multi_configuration/define"

module Wondercap
  class FileReader
    include Logging
    
    def initialize(path, multi_configuration, context)
      @path = path
      @multi_configuration = multi_configuration
      @context = context
    end
    
    def process
      if File.file?(@path)
        logger.debug { "processing configuration file: #{@path}" }
        
        contents = File.new(@path).read
        mc = @multi_configuration
        context_binding = @context.instance_eval do
          extend Wondercap::Define
          @_mc = mc
          def multi_configuration
            @_mc
          end
          binding
        end
        eval(contents, context_binding, @path)
      else
        logger.debug { sprintf("skipping processing of: %s", @path) }
      end
    end
  end
  
  class DirectoryReader
    include Logging
    
    def initialize(path, multi_configuration, context)   
      @path = path
      @multi_configuration = multi_configuration
      @context = context
    end
    
    def process
      logger.debug { sprintf("processing directory: %s", @path) }
      
      if File.directory?(@path)
        (Dir[File.join(@path, "*.mcap")] + Dir[File.join(@path, "*.rb")]).each do |fname|
          FileReader.new(fname, @multi_configuration, @context).process
        end
      end
    end
  end
  
  class FilesReader
    def initialize(multi_configuration, context = Object.new)
      @paths = []
      @multi_configuration = multi_configuration
      @context = context
    end
    
    def paths
      @paths
    end
    
    def process
      @paths.each do |fname|
        if fname =~ %r|/$|
          DirectoryReader.new(fname, @multi_configuration, @context).process
        else
          FileReader.new(fname, @multi_configuration, @context).process
        end        
      end
    end
    
  end
end